import datetime
from django_redis import get_redis_connection
from rest_framework.generics import CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from carts.serializers import CartSerializer
from goods.models import SKU
from orders.serialiers import SaveOrderSerializer


class CartListView(APIView):
    # 必须先让用户登录才能进到订单结算页面
    permission_classes = [IsAuthenticated]

    def get(self, request):

        # 总的逻辑是先取出redis里面的两个数据，hash是了给从mysql中取出的数据增加count和selected属性，set是为了取出所有用户勾选的商品
        # redis取出的数据都是bytes记得转成python 类型的的数据
        # 然后给每一个从mysql取出的sku增加count和selected属性就可以
        # 最后用序列化器序列化输出
        # 响应

        # 获取到用户id
        user_id = request.user.id
        # 构造键去读取redis里面的set集合，全部取出来
        redis_cli = get_redis_connection('cart')
        cart_key = 'cart_%d'%user_id
        cart_select_key = 'cart_select_%d'%user_id

        # 读取redis的商品和数量  也是byte类型
        cart_dict = redis_cli.hgetall(cart_key)  # {sku_id:count,sku_id:count,...}

        # 转换成python类型
        cart_dict2 = {}
        for sku_id, count in cart_dict.items():
            cart_dict2[int(sku_id)] = int(count)

        # 这是一个byte类型的列表
        sku_ids = redis_cli.smembers(cart_select_key)

        # 转成int类型的列表
        sku_ids2 = [int(sku_id) for sku_id in sku_ids]

        # 然后一个个遍历出sku对象　增加count属性
        skus = SKU.objects.filter(pk__in=sku_ids2)
        for sku in skus:
            sku.count = cart_dict2[sku.id]
            sku.selected = True

        # 然后使用序列化器序列化输出
        serializer = CartSerializer(skus, many=True)

        return Response({
            'freight': 10,
            'skus': serializer.data
        })


class SaveOrderView(CreateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = SaveOrderSerializer
